<?php

namespace helper\baidu;

class Translate
{
    private string $host = 'https://fanyi-api.baidu.com/api/trans/vip/translate';

    private string $appId = '20220601001236095';

    private string $appSecret = 'QhB8tkCVzpqImeTLfwRx';

    /**
     * 通用翻译
     * @param string $q
     * @param string $from
     * @param string $to
     * @return mixed
     */
    public function general(string $q, string $from = 'zh', string $to = 'en')
    {
        $param['q'] = $q;
        $param['from'] = $from;
        $param['to'] = $to;
        $param['appid'] = $this->appId;
        $param['salt'] = time();
        $param['sign'] = md5($param['appid'] . $param['q'] . $param['salt'] . $this->appSecret);
        $url = $this->host . '?' . http_build_query($param);
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        if (isset($result['error_code'])) {
            return $result['error_msg'];
        }
        return $result['trans_result'][0]['dst'];
    }
}